package com.kgc.scd.config;

import com.kgc.scd.constant.SendMessageMQConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created On : 2022/11/17 0001.
 * <p>
 * Author : shiguangchuan
 * <p>
 * Description: Fanout扇形模式，自动配置类，自动创建队列，交换机，并将队列绑定到交换机
 */
@Configuration
public class SendMessageMQFanoutConfig {

    /**
     * @author : shiguangchuan
     * @date   : 2022/11/17 0001
     * @param  : []
     * @return : org.springframework.amqp.core.Queue
     * @description : 创建扇形模式，队列one
     */
    @Bean
    public Queue sendResult2User(){
        return new Queue(SendMessageMQConstant.SEND_MASSAGE_RESULT_KH96,true);
    }

    /**
     * @author : shiguangchuan
     * @date   : 2022/11/17 0001
     * @param  : []
     * @return : org.springframework.amqp.core.Queue
     * @description : 创建扇形交换机
     */
    @Bean
    public FanoutExchange sendResultExchange(){
        return new FanoutExchange(SendMessageMQConstant.SEND_MASSAGE_RESULT_EXCHANGE_KH96);
    }

    /**
     * @author : shiguangchuan
     * @date   : 2022/11/17 0001
     * @param  : []
     * @return : org.springframework.amqp.core.Binding
     * @description : 绑定队列one到扇形交换机，不需要指定路由键
     */
    @Bean
    public Binding fanoutBindingQueue(){
        // 绑定队列到扇形交换机，不需要路由键，消息是广播式发送，交换机收到消息，会给所有绑定的队列群发信息（根本没有提供with方法）
        return BindingBuilder.bind(sendResult2User()).to(sendResultExchange());
    }

    /**
     * @author : shiguangchuan
     * @date   : 2022/11/17 0011
     * @param  : [connectionFactory]
     * @return : org.springframework.amqp.rabbit.core.RabbitAdmin
     * @description : 初始化RabbitAdmin对象，实现启动项目自动创建队列和交换机 
     */
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
        // 创建RabbitAdmin对象
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        
        // 设置启动时自动创建
        rabbitAdmin.setAutoStartup(true);
        
        // 创建需要使用的交换机和队列
        rabbitAdmin.declareQueue(sendResult2User());
        rabbitAdmin.declareExchange(sendResultExchange());

        // 返回对象
        return  rabbitAdmin;
    }


}
